package com.alibaba.citrus.ots.common.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component("springApplicationContextUtil")
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    private SpringContextUtil() {
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Autowired
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String beanId) throws BeansException {
        return applicationContext.getBean(beanId);
    }

    public static<T> T getBean(Class<T> clazz) throws BeansException {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return applicationContext.getBean(name, requiredType);
    }

    /**
     * 获取 bean 列表
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> getBeanList(Class<T> clazz){
        String[] beanNamesForType = applicationContext.getBeanNamesForType(clazz);
        if (beanNamesForType == null || beanNamesForType.length == 0) {
            return new ArrayList<>();
        }

        List<T> result = new ArrayList<>();
        Arrays.stream(beanNamesForType).forEach(beanName->{
            result.add(applicationContext.getBean(beanName,clazz));
        });
        return result;
    }
}
